import { useDicts } from '@/layout/hooks/useDictOptions';
import editForm from "./form.vue";
import stockDialog from "./stockDialog.vue";
import feedback from "@/utils/feedback";
import { usePublicHooks } from "@/views/hooks";
import { addDialog, closeDialog, DialogOptions } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw, watch, toRefs } from "vue";
import type { FormItemProps } from "./types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { SuccessFilled, Failed, Edit, } from '@element-plus/icons-vue'
import type { PaginationProps } from "@pureadmin/table";
import { CategoryListTree } from "@/api/pms/catogory";

import { getBrandsByCategoryId } from '@/api/pms/brand';
//api
import {
  AttrGroupList,
  getAttrByGroup
} from "@/api/pms/attr";
import { ProductList, ProductAdd, ProductDetail, ProductEdit, ProductDelete, ProductApproveList, offOrPublish, approve, skuEditStockAndPrice } from '@/api/pms/goods';
import { useDetail } from './util';
import approveForm from "./approveForm.vue";

export function useHook() {
  //表单查询字段
  const form = reactive({
    id: null, //货号
    brandId: null,
    categoryId: null,
    spuName: null,
    publishStatus: null,
    verifyStatus: null,
  });

  const formRef = ref();
  const approveFormRef = ref();
  const stockDialogRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle, switchStyle } = usePublicHooks();
  const categotyList = ref([]);
  const detailInfo = ref({});
  const approveMsgRef = ref(""); //存储审核时的反馈信息

  //查询字典 格式: type1,type2 返回 optionsData.type1 ptionsData.type2
  const { optionsData } = useDicts<any>("sys_yes_no, sys_common_status")

  const { toDetail, router } = useDetail();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  //表格字段
  const columns: TableColumnList = [

    {
      label: "id",
      prop: "id",
      align: "left",
      minWidth: 200,
    },
    {
      label: "图片",
      prop: "productImage",
      minWidth: 200,
      cellRenderer: ({ row }) => (
        <el-image
          preview-teleported={true}
          src={row.productImage}
          preview-src-list={Array.of(row.productImage)}
          class="w-[100px] h-[100px] "
        />
      ),
    },
    {
      label: "商品名称",
      prop: "name",
      minWidth: 220,
      cellRenderer: scope => (
        <div style="width:200px;    
        box-sizing: border-box;
    white-space: normal;
    word-break: break-all;
    line-height: 23px;"> {scope.row.name}</div>
      )
    },
    {
      label: "品牌分类",
      prop: "brandName",
      minWidth: 200,
      cellRenderer: scope => (
        <div>
          <span>品牌:</span> <span>{scope.row.brandName}</span>
          <br></br>
          <span>分类:</span> <span>{scope.row.productCategoryName}</span>
        </div>

      )
    },
    {
      label: "价格",
      prop: "price",
      minWidth: 200,
      cellRenderer: scope => (
        <div>
          <span>售价:</span> <span>￥{Number(scope.row.price) / 100}</span>
          <br></br>
          <span>市场价:</span> <span>￥{Number(scope.row.originalPrice) / 100}</span>
        </div>

      )
    },

    {
      label: "库存",
      prop: "stock",
      minWidth: 200,
      cellRenderer: scope => (
        <el-button type="primary" icon={Edit} circle onClick={() => showStockForm(scope.row.id)} />

      ),
    },
    {
      label: "销量",
      prop: "sale",
      minWidth: 200,
    },

    {
      label: "上架状态",
      prop: "publishStatus",
      minWidth: 200,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          v-model={scope.row.publishStatus}
          active-value={1}
          inactive-value={0}
          active-text="上架"
          inactive-text="下架"
          inline-prompt
          style={switchStyle.value}
          onChange={() => changePublishStatus(scope as any)}
        />
      ),
    },
    {
      label: "审核状态",
      prop: "verifyStatus",
      minWidth: 200,
      showOverflowTooltip: false,
      cellRenderer: scope => (
        <div>
          <span style="margin: 0 auto;">{scope.row.verifyStatus == "0" ? "未审核" : (scope.row.verifyStatus == "1" ? "审核通过" : "审核拒绝")}</span><br></br>
          {<>
            <el-button type="primary" size="small" plain onClick={() => getApproveList(scope.row.id)}>记录</el-button>
            {scope.row.verifyStatus != '1' ? <el-button type="primary" size="small" plain onClick={() => approveDialog(scope.row.id)}>审核</el-button> : ''}
          </>
          }
        </div>
      ),

    },


    {
      label: "启用状态",
      prop: "enable",
      minWidth: 200,
      formatter: ({ enable }) => (enable == "0" ? "禁用 " : "启用"),
    },
    // {
    //   label: "创建时间",
    //   minWidth: 200,
    //   prop: "createTime",
    // },

    // {
    //   label: "备注",
    //   prop: "remark",
    //   minWidth: 200
    // },


    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];


  async function onSearchCategoty() {
    const result = await CategoryListTree({}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    if (result.success) {
      categotyList.value = result.data;
      optionsData.categotyList = result.data;
      return result.data
    }
    return null;
  }
  /**
   * 根据分类获取品牌
   * @param cid 
   */
  async function getBrandByCd(cid: any) {
    let res = await getBrandsByCategoryId(cid);
    if (res.success) {
      return res.data;
    } return null;
  }


  /**
   * 获取分类下的属性分组
   * @param cId  分类id
   */
  async function getAttrGroups(cId: any) {
    let res = await AttrGroupList({
      cid: cId,
      pageIndex: 1,
      pageSize: 9999
    })
    if (res && res.code == 200) {
      return res.data;
    }
    return null;

  }

  /**
     * 获取分类和分组下的属性列表
     * @param params 
     */
  async function getAttrByGroupAndCid(cid: any, gid: any, attrType: number = 1) {
    let res = await AttrGroupList({
      id: gid,
      cid: cid,
      attrType,
      pageIndex: 1,
      pageSize: 9999
    })
    if (res && res.code == 200) {
      return res.data;
    }
    return null;

  }


  /**
   * 展示修改库存弹窗
   * @param scope 
   */
  async function showStockForm(spuId: any) {

    await loadGoodDetail({ id: spuId });
    if (!detailInfo.value || !detailInfo.value.id) {
      return;
    }

    addDialog({
      title: "修改库存",
      footerButtons: [
        {
          label: "取消",
          size: "small",

          btnClick: ({ dialog: { options, index }, button }) => {
            console.log(options, index, button);
            editStock(1, options, index);
          }
        },

        {
          label: "确定",
          size: "small",
          type: "primary",
          btnClick: ({ dialog: { options, index }, button }) => {
            console.log(options, index, button);
            editStock(2, options, index);
          }
        }
      ],
      props: {
        formInline: {
          id: spuId,
          skuList: detailInfo.value.skuInfos
        }
      },
      width: "50%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(stockDialog, { ref: stockDialogRef }),

    });


  }


  /**
   * 
   * @param type 1 取消 2:修改
   * @param options 
   * @param index 
   */
  function editStock(type: number, options: DialogOptions, index: number) {
    if (type == 1) {
      closeDialog(options, index);
      return;
    }
    let data = JSON.parse(JSON.stringify(options.props.formInline));
    data.skuList.forEach(p => {
      //将元转换为分保存
      p.price = Number(p.price) * 100;
    });

    skuEditStockAndPrice(data.id, data.skuList).then(res => {
      if (res.code == 200) {
        onSearch();
        return;
      }

    }).finally(() => {
      closeDialog(options, index);
    })




  }


  /**
   * 改变上架状态事件
   * @param scope 
   */
  function changePublishStatus(scope: any) {
    console.log("row", scope);
    offOrPublish(scope.row.id, scope.row.publishStatus).then(res => {
      if (res.code == 200) {
        onSearch();
        return;
      }
      scope.row.publishStatus = scope.row.publishStatus == '0' ? 1 : 0;
      feedback.msgError(res.message);
    }).catch(err => {
      scope.row.publishStatus = scope.row.publishStatus == '0' ? 1 : 0;
    })
  }


  function approveDialog(productId: any) {
    addDialog({
      title: "审核商品",
      footerButtons: [
        {
          label: "通过",
          size: "small",
          type: "success",
          btnClick: ({ dialog: { options, index }, button }) => {
            console.log(options, index, button);
            approveHandle(productId, 1, options, index);
          }
        },

        {
          label: "拒绝",
          size: "small",
          type: "warning",
          btnClick: ({ dialog: { options, index }, button }) => {
            console.log(options, index, button);
            approveHandle(productId, 2, options, index);
          }
        }
      ],
      contentRenderer: ({ options, index }) => (
        <el-input
          v-model={approveMsgRef.value}
          style="width: 100%;"
          rows="5"
          type="textarea"
          placeholder="请输入反馈信息"
        />

      )

    });
  }

  function approveHandle(productId: String, status: number, options: DialogOptions, index: number) {
    let data = {
      productId,
      status,
      remark: approveMsgRef.value
    };
    console.log("approve data", data);
    approve(data).then(res => {
      if (res.code == 200) {
        feedback.msgSuccess("操作成功!");
        onSearch();
        closeDialog(options, index);
      } else {
        feedback.msgError(res.message);
      }
    });
  }





  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }


  /**
 * 页数改变
 * @param val 
 */

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  /**
   * 页码改变
   * @param val 
   */
  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }
  async function onSearch() {
    loading.value = true;
    let params = toRaw(form);
    params.pageIndex = pagination.currentPage;
    params.pageSize = pagination.pageSize;
    console.log("params---->", params);
    ProductList(form).then(result => {

      if (result.success) {
        dataList.value = result.data;
        pagination.total = result.total;
        pagination.pageSize = result.pageSize;
        pagination.currentPage = result.pageIndex;

      }
    }).finally(() => {
      loading.value = false;
    });



  }

  /**
   * 获取商品详情 
   * 组装详细信息
   * @param row 
   */
  async function loadGoodDetail(row) {
    console.log("row", row);

    let res = await ProductDetail({ spuId: row.id });
    console.log("details res", res);
    if (res.code != 200) {
      feedback.msgError(res.message);
      return;
    }
    detailInfo.value = res.data;

  }



  /**
   * 获取审核记录列表 
   * 组装为timeLine组件需要的格式
   * @param productId 
   */
  async function getApproveList(productId: any) {
    let res = await ProductApproveList(productId);
    console.log("getApproveList--res", res);

    if (res.code == 200) {
      let timeLineData = new Array();
      for (let index = 0; index < res.data.length; index++) {
        const element = res.data[index];
        timeLineData.push({
          content: element.detail,
          timestamp: element.createTime,
          color: element.status == 1 ? "#0bbd87" : "#F56C6C",
          icon: element.status == 1 ? SuccessFilled : Failed,
        });


      }
      if (timeLineData.length > 0) {
        openApproveDialog(timeLineData);
      } else {
        feedback.notifySuccess("没有审核记录!");
      }

    }
    return null;
  }

  /**
   * 弹出审核记录时间框
   * @param params 
   */
  function openApproveDialog(row?: any) {

    addDialog({
      title: "审核记录",
      props: {
        formInline: {
          data: row
        }
      },
      width: "50%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(approveForm, { ref: approveFormRef }),

    });


  }


  /**
   * 装载转换其他数据
   * @param treeList
   * @returns
   */
  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  async function openDialog(title = "新增", row?: FormItemProps) {
    console.log("row", row);
    if (row) {
      await loadGoodDetail(row);
    }
    console.log("detailInfo.value", detailInfo.value);

    // if (title == "新增") {
    //   toDetail({ id: 0 }, 'query');
    //   return;
    // }
    let item = detailInfo.value;
    addDialog({
      title: title,
      props: {
        formInline: {
          higherOptions: formatHigherDeptOptions(cloneDeep(dataList.value)),//状态其他数据
          dictOptionData: optionsData,
          id: row?.id,
          name: item?.name,
          picUrl: item?.picUrl,
          subPicUrls: item?.subPicUrls,
          subTitle: item?.subTitle, //副标题
          productCategoryId: item?.productCategoryId,
          platformCategoryId: item?.platformCategoryId,
          brandId: item?.brandId,
          freightTemplateId: item?.freightTemplateId,
          productSn: item?.productSn, //货号
          feedings: item?.feedings, //加料
          publishing: item?.publishing == true ? 1 : 0, //是否发布
          newGoods: item?.newGoods == true ? 1 : 0, //是否新品
          recommend: item?.recommend == true ? 1 : 0, //是否推荐
          unit: item?.unit,
          weight: item?.weight ?? 0, //重量
          giftGrowth: item?.giftGrowth ?? 0, //成长值
          giftPoint: item?.giftPoint ?? 0, //赠送积分
          usePointLimit: item?.usePointLimit ?? 0, //限制使用积分数
          attrGroupId: -1, //属性分组id
          baseAttrs: item?.baseAttrs ?? [], //基本属性列表
          skuList: item?.skuInfos ?? [], //sku规格列表 包含库存的格式
          specList: item?.specList ?? [], // 规格列表  不包含库存的格式
          sort: item?.sort ?? 0,
          detailHtml: item?.detailHtml ?? '', //pc端详情
          detailMobileHtml: item?.detailMobileHtml ?? '', //移动端详情
          manySku: false, //是否多规格
        }
      },
      width: "80%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      hideFooter: true,//关闭按钮
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores(isAdd: Boolean) {
          if (isAdd) {
            ProductAdd(curData).then((result) => {
              if (result.success) {
                feedback.msgSuccess("操作成功");
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              }
            }).catch((err) => {
              feedback.msgError(err.message ? err.message : `操作失败`);
            });

          } else {
            ProductEdit(curData).then((result) => {
              if (result.success) {
                feedback.msgSuccess(`操作成功`);
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              }
            }).catch((err) => {
              feedback.msgError(err.message ? err.message : `操作失败`);
            });
          }
        }

        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              chores(true)
            } else {
              chores(false)
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {

    ProductDelete([row.id]).then((result) => {
      feedback.msgSuccess("操作成功")
      onSearch();
    }).catch((err) => {
      feedback.msgError(err && err.message ? err.message : "操作失败")
    });

  }

  onMounted(() => {
    onSearch();
    onSearchCategoty()
  });

  return {
    form,
    loading,
    columns,
    dataList,
    optionsData,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改 */
    openDialog,
    /** 删除 */
    handleDelete,
    pagination,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    onSearchCategoty,
    getBrandByCd,
    loadGoodDetail,
    getAttrGroups,
    getAttrByGroupAndCid

  };
}